﻿using Dynamics.NAV.Metro.Common;
using Okra.Data;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dynamics.NAV.Metro.Data
{
    public class NavItemDataListSource : PagedDataListSource<NavItem>
    {
        private string _filter;
        private int _pageSize = SettingsStorage.GetLocalSetting<int>(App.DEFAULT_REC_PER_PAGE_KEY);
        private IDynamicsNavApi _navApi;

        public NavItemDataListSource()
        {
            _navApi = new DynamicsNavApi();
            this._filter = string.Empty;
        }

        public NavItemDataListSource(int pageSize)
        {
            _navApi = new DynamicsNavApi();
            this._filter = string.Empty;
            if (pageSize > 0)
                this._pageSize = pageSize;
        }

        public NavItemDataListSource(string filter)
        {
            _navApi = new DynamicsNavApi();
            this._filter = filter;
        }

        public NavItemDataListSource(string filter, int pageSize)
        {
            _navApi = new DynamicsNavApi();
            this._filter = filter;
            if (pageSize > 0)
                this._pageSize = pageSize;
        }

        protected async override Task<DataListPageResult<NavItem>> FetchCountAsync()
        {
            int count = await _navApi.GetItemCount(1000, "Metro_Item", this._filter);

            return new DataListPageResult<NavItem>(count , this._pageSize, null, null);
        }

        protected override Task<DataListPageResult<NavItem>> FetchPageSizeAsync()
        {
            return Task.FromResult(new DataListPageResult<NavItem>(null, this._pageSize, null, null));
        }

        protected async override Task<DataListPageResult<NavItem>> FetchPageAsync(int pageNumber)
        {
            // Retrieve a page at a time (params are skip & top)
            NavItemPage ItemPage = await _navApi.GetItems<NavItemPage>((pageNumber - 1) * this._pageSize, this._pageSize, "Metro_Item", this._filter);

            return new DataListPageResult<NavItem>(null, this._pageSize, pageNumber, ItemPage.Items);
        }
    }
}
